

from rest_framework.views import  APIView
from rest_framework.response import Response
from api.utils.auth import LoginAuth
from api.models import *
from api.utils.response import BaseResponse
from api.utils.exceptions import CommonExcetpion
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
import redis
import json

cache = redis.Redis(decode_responses=True)

class ShoppingCartView(APIView):
    authentication_classes = [LoginAuth]
    def post(self,request):
        """
        状态码：
            1000 成功
            1001 课程不存在

        模拟请求数据
        {
        "course_id": 1,
        "price_policy_id":2
        }
        :param request:
        :return:
        """
        # 1 获取请求数据
        course_id = request.data.get("course_id")
        price_policy_id = request.data.get("price_policy_id")
        user_id = request.user.pk

        res = BaseResponse()

        try:
            # 2 校验数据
            # 2.1 校验课程是否存在
            course_obj = Course.objects.get(pk=course_id)
            # 2.2 校验价格策略是否合法
            price_policy_dict = {}
            for price_policy in course_obj.price_policy.all():
                price_policy_dict[price_policy.pk] = {
                    "pk":price_policy.pk,
                    "valid_period":price_policy.valid_period,
                    "valid_period_text":price_policy.get_valid_period_display(),
                    "price":price_policy.price,
                    "default": price_policy_id == price_policy.pk
                }
            print(price_policy_dict)
            if price_policy_id not in [obj.pk for obj in course_obj.price_policy.all()]:
                raise CommonExcetpion(1002,"价格策略错误")
            # 选中的价格策略
            pp = PricePolicy.objects.get(pk=price_policy_id)

            # 3.写入redis
            shoppingcar_key = settings.SHOPPINGCAR_KEY%(user_id,course_id)

            shoppingcar_val = {
                "title":course_obj.name,
                "img":course_obj.course_img,
                "relate_price_policy":price_policy_dict,
                "choose_price_policy_id":price_policy_id ,
                "price":pp.price,
                "valid_period":pp.valid_period,
                "valid_period_text":pp.get_valid_period_display(),
            }

            cache.set(shoppingcar_key,json.dumps(shoppingcar_val))

            res.data = "加入购物车成功！"

            """
                REDIS = {
                # 方案一
                    user_id: {
                        shoppingcart:{
                            "course_id":{
                                "title":"...",
                                "img": "..."
                            }
                        }
                    }
                }
                
                # 方案二
                REDIS = {
                    shoppingcar_userid_courseid:{
                        "title":"...",
                        "img":"..."
                    }
                }

            """

        except CommonExcetpion as e:
            res.code = e.code
            res.msg = e.msg

        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = "课程不存在"

        return Response(res.dict)

    def get(self,request):
        res = BaseResponse()
        try:
            # 1.获取用户
            user_id = request.user.id
            # 2.拼接购物车key
            # shoppingcar_1_*
            shopping_car_key = settings.SHOPPINGCAR_KEY%(user_id,"*")

            # 3.去redis读取用户的所有加入购物车的课程
            # 3.1先去模糊匹配出所有符合要求的key

            all_keys = cache.keys(shopping_car_key)

            # all_keys = REDIS_CONN.scan_iter(shopping_car_key)
            print(all_keys)

            shopping_car_list = []
            for key in all_keys:
                print(key)
                course_info = json.loads(cache.get(key))
                print(course_info)
                shopping_car_list.append(course_info)

                res.data = {"shopping_car_list":shopping_car_list,"total":len(shopping_car_list)}

        except Exception as e:
            pass

        return Response(res.dict)